package com.example.demo.yuy.adminConsole.service;

import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2018/9/21.
 */
@Service
public class DownLoad extends HttpServlet {

    // 下载
    public String doGet(HttpServletRequest request, HttpServletResponse response, String path)
        throws ServletException, IOException {
        //根据路径获取文件
        File file = new File(path);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="
            + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));

        //将文件读取出来，写入到response的outputStream中
        try {
            InputStream is = new FileInputStream(file);            //根据文件获取输入流
            OutputStream os = response.getOutputStream();        //获取ServletOutputStream输出流
            byte[] b = new byte[1024];
            int length;


            //依次将输入流数据写入输出流
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";

    }
}

